package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.DevelopmentTop;
import com.ruoyi.system.mapper.DevelopmentTopMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.CommunityBusinessTargetMapper;
import com.ruoyi.system.domain.CommunityBusinessTarget;
import com.ruoyi.system.service.ICommunityBusinessTargetService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Validator;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;

/**
 * 小区业务目标Service业务层处理
 * 
 * @author alex
 * @date 2025-08-05
 */
@Service
public class CommunityBusinessTargetServiceImpl implements ICommunityBusinessTargetService 
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    private CommunityBusinessTargetMapper communityBusinessTargetMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private DevelopmentTopMapper developmentTopMapper;



    @Autowired
    protected Validator validator;

    /**
     * 查询小区业务目标
     * 
     * @param id 小区业务目标主键
     * @return 小区业务目标
     */
    @Override
    public CommunityBusinessTarget selectCommunityBusinessTargetById(Long id)
    {
        return communityBusinessTargetMapper.selectCommunityBusinessTargetById(id);
    }

    /**
     * 查询小区业务目标列表
     * 
     * @param communityBusinessTarget 小区业务目标
     * @return 小区业务目标
     */
    @Override
    @DataScope(deptAlias="d")
    public List<CommunityBusinessTarget> selectCommunityBusinessTargetList(CommunityBusinessTarget communityBusinessTarget)
    {
        return communityBusinessTargetMapper.selectCommunityBusinessTargetList(communityBusinessTarget);
    }

    /**
     * 新增小区业务目标
     * 
     * @param communityBusinessTarget 小区业务目标
     * @return 结果
     */
    @Override
    public int insertCommunityBusinessTarget(CommunityBusinessTarget communityBusinessTarget)
    {
        // 根据小区名称查找同名小区，将之前的数据status字段更改为0
        if (communityBusinessTarget.getCommunityName() != null && !communityBusinessTarget.getCommunityName().trim().isEmpty()) {
            List<CommunityBusinessTarget> existingTargets = communityBusinessTargetMapper.selectCommunityBusinessTargetByCommunityName(communityBusinessTarget.getCommunityName().trim());
            if (existingTargets != null && !existingTargets.isEmpty()) {
                // 提取所有同名小区的ID
                Long[] existingIds = existingTargets.stream()
                    .map(CommunityBusinessTarget::getId)
                    .toArray(Long[]::new);
                // 批量将status设置为0
                communityBusinessTargetMapper.updateCommunityBusinessTargetStatusByIds(existingIds, "0");
            }
        }
        
        communityBusinessTarget.setCreateTime(DateUtils.getNowDate());
        return communityBusinessTargetMapper.insertCommunityBusinessTarget(communityBusinessTarget);
    }

    /**
     * 修改小区业务目标
     * 
     * @param communityBusinessTarget 小区业务目标
     * @return 结果
     */
    @Override
    public int updateCommunityBusinessTarget(CommunityBusinessTarget communityBusinessTarget)
    {
        // 如果修改了小区名称，需要确保同名小区的唯一性
        if (communityBusinessTarget.getCommunityName() != null && !communityBusinessTarget.getCommunityName().trim().isEmpty() && communityBusinessTarget.getId() != null) {
            List<CommunityBusinessTarget> existingTargets = communityBusinessTargetMapper.selectCommunityBusinessTargetByCommunityName(communityBusinessTarget.getCommunityName().trim());
            if (existingTargets != null && !existingTargets.isEmpty()) {
                // 过滤掉当前要更新的记录，只处理其他同名记录
                List<Long> otherIds = existingTargets.stream()
                    .filter(existing -> !existing.getId().equals(communityBusinessTarget.getId()))
                    .map(CommunityBusinessTarget::getId)
                    .collect(java.util.stream.Collectors.toList());
                
                if (!otherIds.isEmpty()) {
                    // 批量将其他同名小区的status设置为0
                    Long[] otherIdsArray = otherIds.toArray(new Long[0]);
                    communityBusinessTargetMapper.updateCommunityBusinessTargetStatusByIds(otherIdsArray, "0");
                }
            }
        }
        
        communityBusinessTarget.setUpdateTime(DateUtils.getNowDate());
        return communityBusinessTargetMapper.updateCommunityBusinessTarget(communityBusinessTarget);
    }

    /**
     * 批量删除小区业务目标
     * 
     * @param ids 需要删除的小区业务目标主键
     * @return 结果
     */
    @Override
    public int deleteCommunityBusinessTargetByIds(Long[] ids)
    {
        return communityBusinessTargetMapper.deleteCommunityBusinessTargetByIds(ids);
    }

    /**
     * 删除小区业务目标信息
     * 
     * @param id 小区业务目标主键
     * @return 结果
     */
    @Override
    public int deleteCommunityBusinessTargetById(Long id)
    {
        return communityBusinessTargetMapper.deleteCommunityBusinessTargetById(id);
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<CommunityBusinessTarget> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (CommunityBusinessTarget user : userList)
        {
            try
            {
                // 根据 DeptName 查询部门
                SysDept sysDept = new SysDept();
                sysDept.setDeptName(user.getCommunityName());
                List<SysDept> sysDepts = deptMapper.selectDeptList(sysDept);
                if (sysDepts == null || sysDepts.isEmpty()) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、部门 " + user.getCommunityName() + " 不存在");
                    continue;
                }
                // 查到部门，先删除同一个deptId的记录，再插入业务目标表
                Long deptId = sysDepts.get(0).getDeptId();
                user.setDeptId(deptId);
                
                // 删除同一个deptId的现有记录，确保唯一性
                CommunityBusinessTarget queryTarget = new CommunityBusinessTarget();
                queryTarget.setDeptId(deptId);
                List<CommunityBusinessTarget> existingTargets = communityBusinessTargetMapper.selectCommunityBusinessTargetList(queryTarget);
                if (existingTargets != null && !existingTargets.isEmpty()) {
                    for (CommunityBusinessTarget existing : existingTargets) {
                        communityBusinessTargetMapper.deleteCommunityBusinessTargetById(existing.getId());
                    }
                }
                
                user.setCreateBy(operName);
                user.setStatus("1");
                communityBusinessTargetMapper.insertCommunityBusinessTarget(user);
                successNum++;
                successMsg.append("<br/>" + successNum + "、部门 " + user.getCommunityName() + " 导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、部门 " + user.getCommunityName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


    /**
     * 导入小区实时数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importTimeUser(List<CommunityBusinessTarget> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (CommunityBusinessTarget user : userList)
        {
            try
            {
                // 根据 DeptName 查询部门
                SysDept sysDept = new SysDept();
                sysDept.setDeptName(user.getCommunityName());
                List<SysDept> sysDepts = deptMapper.selectDeptList(sysDept);
                if (sysDepts == null || sysDepts.isEmpty()) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、部门 " + user.getCommunityName() + " 不存在");
                    continue;
                }
                
                // 查到部门，设置部门ID
                Long deptId = sysDepts.get(0).getDeptId();
                user.setDeptId(deptId);
                
                // 删除该部门的所有记录，确保deptId唯一性
                CommunityBusinessTarget queryTarget = new CommunityBusinessTarget();
                queryTarget.setDeptId(deptId);
                List<CommunityBusinessTarget> existingTargets = communityBusinessTargetMapper.selectCommunityBusinessTargetList(queryTarget);
                if (existingTargets != null && !existingTargets.isEmpty()) {
                    for (CommunityBusinessTarget existing : existingTargets) {
                        communityBusinessTargetMapper.deleteCommunityBusinessTargetById(existing.getId());
                    }
                }
                
                // 插入新数据
                user.setCreateBy(operName);
                communityBusinessTargetMapper.insertCommunityBusinessTarget(user);
                successNum++;
                successMsg.append("<br/>" + successNum + "、部门 " + user.getCommunityName() + " 导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、部门 " + user.getCommunityName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 根据部门ID列表查询小区业务目标
     * @param deptIds 部门ID列表
     * @return 小区业务目标列表
     */
    @Override
    public List<CommunityBusinessTarget> selectCommunityBusinessTargetByDeptIds(List<Long> deptIds) {
        if (deptIds == null || deptIds.isEmpty()) {
            return java.util.Collections.emptyList();
        }
        return communityBusinessTargetMapper.selectCommunityBusinessTargetByDeptIds(deptIds);
    }

    /**
     * 根据部门ID列表和时间范围查询小区业务目标
     * @param deptIds 部门ID列表
     * @param targetTime 目标时间
     * @return 小区业务目标列表
     */
    @Override
    public List<CommunityBusinessTarget> selectCommunityBusinessTargetByDeptIdsAndTime(List<Long> deptIds, Date targetTime) {
        if (deptIds == null || deptIds.isEmpty()) {
            return java.util.Collections.emptyList();
        }
        return communityBusinessTargetMapper.selectCommunityBusinessTargetByDeptIdsAndTime(deptIds, targetTime);
    }

    /**
     * 根据状态查询小区列表（基于活动时间判断）
     * 
     * @param status 状态：0-已完成，1-计划开展
     * @return 小区业务目标集合
     */
    @Override
    public List<CommunityBusinessTarget> selectCommunityBusinessTargetByStatus(String status) {
        // 获取所有小区业务目标
        List<CommunityBusinessTarget> allTargets = communityBusinessTargetMapper.selectCommunityBusinessTargetList(new CommunityBusinessTarget());
        
        if (allTargets == null || allTargets.isEmpty()) {
            return java.util.Collections.emptyList();
        }
        
        // 获取当前时间
        java.util.Date currentDate = new java.util.Date();
        java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
        
        List<CommunityBusinessTarget> result = new java.util.ArrayList<>();
        
        for (CommunityBusinessTarget target : allTargets) {
            try {
                String activityStartTime = target.getActivityStartTime();
                String activityEndTime = target.getActivityEndTime();
                
                // 如果活动时间字段为空，跳过该记录
                if (activityStartTime == null || activityStartTime.trim().isEmpty() ||
                    activityEndTime == null || activityEndTime.trim().isEmpty()) {
                    continue;
                }
                
                java.util.Date startDate = dateFormat.parse(activityStartTime.trim());
                java.util.Date endDate = dateFormat.parse(activityEndTime.trim());
                
                if ("1".equals(status)) {
                    // 计划开展：当前时间早于活动结束时间
                    if (currentDate.before(endDate)) {
                        result.add(target);
                    }
                } else if ("0".equals(status)) {
                    // 已完成：当前时间晚于活动结束时间
                    if (currentDate.after(endDate)) {
                        result.add(target);
                    }
                }
            } catch (java.text.ParseException e) {
                // 日期解析失败，跳过该记录
                 log.warn("日期解析失败，小区ID: {}, 活动开始时间: {}, 活动结束时间: {}", 
                     target.getId(), target.getActivityStartTime(), target.getActivityEndTime());
                continue;
            }
        }
        
        return result;
    }

    @Override
    public List<Map<String, Object>> countByRanking(Long deptId) {
        // 获取所有子部门（小区）
        List<SysDept> sysDepts = deptMapper.selectChildrenDeptById(deptId);
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (SysDept sysDept : sysDepts) {
            Long currentDeptId = sysDept.getDeptId();
            String deptName = sysDept.getDeptName();
            // 查出该小区所有业务目标数据
            List<CommunityBusinessTarget> targets = communityBusinessTargetMapper.selectCommunityBusinessTargetByDeptIds(java.util.Collections.singletonList(currentDeptId));
            // 目标值（status=0）
            CommunityBusinessTarget targetRow = targets.stream().filter(t -> "0".equals(t.getStatus())).findFirst().orElse(null);
            int targetConvergence = targetRow != null ? parseIntSafe(targetRow.getConvergenceTarget()) : 0; // 全量融合
            int targetBroadband = targetRow != null ? parseIntSafe(targetRow.getSingleBroadbandTarget()) : 0; // 宽带
            int targetFttr = targetRow != null ? parseIntSafe(targetRow.getFttrTarget()) : 0; // FTTR
            int targetQuality = targetRow != null ? parseIntSafe(targetRow.getQualityRepair()) : 0; // 质差修复

            // 实际值通过developmentTopMapper查所有工号累加
            DevelopmentTop developmentTop = new DevelopmentTop();
            developmentTop.setDeptId(currentDeptId);
            developmentTop.setDeptName(deptName);
            List<DevelopmentTop> developmentTops = developmentTopMapper.selectDevelopmentTopList(developmentTop);
            int actualConvergence = 0; // 全量融合
            int actualBroadband = 0;   // 宽带
            int actualFttr = 0;        // FTTR
            int actualQuality = 0;     // 质差修复
            for (DevelopmentTop dev : developmentTops) {
                actualConvergence += parseIntSafe(dev.getFullFusion());
                actualBroadband += parseIntSafe(dev.getBroadband());
                actualFttr += parseIntSafe(dev.getFttr());
                actualQuality += parseIntSafe(dev.getPoorRepair());
            }

            // 权重
            double wConvergence = 30.0, wBroadband = 25.0, wFttr = 25.0, wQuality = 20.0;

            // 单项得分，单项最多1.2倍权重
            double scoreConvergence = targetConvergence == 0 ? 0 : Math.min((actualConvergence * 1.0 / targetConvergence) * wConvergence, wConvergence * 1.2);
            double scoreBroadband = targetBroadband == 0 ? 0 : Math.min((actualBroadband * 1.0 / targetBroadband) * wBroadband, wBroadband * 1.2);
            double scoreFttr = targetFttr == 0 ? 0 : Math.min((actualFttr * 1.0 / targetFttr) * wFttr, wFttr * 1.2);
            double scoreQuality = targetQuality == 0 ? 0 : Math.min((actualQuality * 1.0 / targetQuality) * wQuality, wQuality * 1.2);

            // 总分
            double totalScore = scoreConvergence + scoreBroadband + scoreFttr + scoreQuality;
            totalScore = Math.round(totalScore * 100.0) / 100.0;
            String percent = totalScore + "";

            // 是否完成
            int finished = totalScore >= 100.0 ? 1 : 2;

            // 组装结果
            Map<String, Object> map = new HashMap<>();
            map.put("deptName", deptName);
            map.put("percent", percent);
            map.put("finished", finished);
            resultList.add(map);
        }
        return resultList;
    }

    // 工具方法：安全转int
    private int parseIntSafe(String s) {
        try {
            if (s == null || s.trim().isEmpty()) return 0;
            return Integer.parseInt(s.trim());
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 查询未开展小区列表
     * 返回第四级所有小区和第三级中不包含'营业部'的小区中未在小区业务目标表中的小区
     * 
     * @return 未开展小区列表
     */
    @Override
    public List<SysDept> selectUnstartedCommunities() {
        try {
            List<SysDept> allDepts = deptMapper.selectDeptList(new SysDept());
            List<SysDept> allCommunities = new ArrayList<>();
            
            for (SysDept dept : allDepts) {
                if (dept.getAncestors() != null && 
                    "0".equals(dept.getStatus()) && 
                    "0".equals(dept.getDelFlag())) {
                    
                    String[] ancestors = dept.getAncestors().split(",");
                    
                    // 第四级小区（ancestors包含三个逗号）
                    if (ancestors.length == 3) {
                        allCommunities.add(dept);
                    }
                    // 第三级小区（ancestors包含两个逗号）且名称不包含'营业部'
                    else if (ancestors.length == 2 && 
                             dept.getDeptName() != null && 
                             !dept.getDeptName().contains("营业部")) {
                        allCommunities.add(dept);
                    }
                }
            }
            
            log.info("查询到符合条件的小区总数: {}", allCommunities.size());
            
            // 2. 查询所有已有业务目标的小区部门ID
            List<CommunityBusinessTarget> allTargets = communityBusinessTargetMapper.selectCommunityBusinessTargetList(new CommunityBusinessTarget());
            List<Long> targetDeptIds = allTargets.stream()
                .map(CommunityBusinessTarget::getDeptId)
                .filter(deptId -> deptId != null)
                .collect(Collectors.toList());
            
            // 3. 筛选出未开展的小区
            List<SysDept> unstartedCommunities = allCommunities.stream()
                .filter(dept -> !targetDeptIds.contains(dept.getDeptId()))
                .collect(Collectors.toList());
            
            log.info("查询到未开展小区数量: {}", unstartedCommunities.size());
            
            return unstartedCommunities;
            
        } catch (Exception e) {
            log.error("查询未开展小区列表失败", e);
            return new ArrayList<>();
        }
    }
}
